/*********************************************************************************
 *      Copyright:  (C) 2020 chenxiaohong<www.530990157@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  get_data.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(20/06/20)
 *         Author:  chenxiaohong <www.530990157@qq.com>
 *      ChangeLog:  1, Release initial version on "20/06/20 12:55:46"
 *                 
 ********************************************************************************/
#include<stdio.h>
#include<sqlite3.h>
#include<string.h>
#include<syslog.h>
#include"json_client.h"

int get_data_from_database(sqlite3 *db, char *json_buf)
{
    char          *errmsg;
    char          **dbResult;
    int           nRow,nColumn;
    
    memset(json_buf, 0, strlen(json_buf));

    if(sqlite3_get_table(db,"select * from JSON",&dbResult,&nRow,&nColumn,&errmsg) != SQLITE_OK)
    {   
        printf("Seek Massage from database failure\n");
        return -1; 
    }   
    
    if(!nRow)
    {   
        printf("There is no massage in database\n");
        return -2;
    }   
    
    memcpy(json_buf,dbResult[1], strlen(json_buf));
    
    return 1;
}

int delete_data_from_database(sqlite3 *db)
{
    char            *errmsg = NULL;
    
    if(sqlite3_exec(db,"delete from JSON where data = (select data from JSON limit 1);",NULL,NULL,&errmsg) != SQLITE_OK)
    {   
        printf("Delete the first massage from table failure:%s\n",errmsg);
        return 1;
    }   
    
    return 1;
}

int save_data_in_database(sqlite3 *db, char *json_buf)
{
    char             sql[56] = {0};
    char            *errmsg = NULL;
    
    sprintf(sql,"insert into JSON values ('%s');", json_buf);
    if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
    {   
        printf("Save tlv buf to database failure:%s\n",errmsg);
        return -1; 
    }
    return 1;
}
